<template>
  <div class="v-editor-select">
    <MDropdown
      :disabled="row.readonly || isModelDisabled"
      lazy
      :loadListCallback="loadOptions"
    >
      <div class="g-jc-sb g-pd-l-8 g-pointer">
        <div class="g-flex-1">
          {{ locale.getTByKey(selectedValue, selectedValue) }}
        </div>
        <div
          v-if="selected && !row.readonly && !isModelDisabled"
          class="g-flex-0 g-pd-lr-4"
        >
          <img
            src="statics/icons/app/iconlist2.png"
            @click="handleClick"
          />
        </div>
      </div>
      <template #dropdown>
        <MDropdownMenuItem
          v-for="item in options"
          :key="item.value"
          class="g-one-line"
          @click="handleClickItem(item)"
        >
          {{ locale.getTByContent(item, item.label, { en: "enLabel", zhCn: "label" }) }}
        </MDropdownMenuItem>
      </template>
    </MDropdown>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, Ref, inject } from "vue";
import { ModelValue, PropertyDropdownOption, PropertyRow } from "../../types";
import { propertyUtil } from "../../PropertyUtil";
import { BusEvent, PropertyKey } from "@/constants/Enums";
import MDropdown from "@/common/dropdown/Dropdown.vue";
import MDropdownMenuItem from "@/common/dropdown/DropdownMenuItem.vue";
import { locale } from "@/util/locale";
import { modelService } from "@/modules/model/service";
import { useLoadItemsOptions } from "./useLoadOptions";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

/**
 * 普通下拉选择，处理枚举型属性的拉下选择 比如属性的可见性 visibility
 */
const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
}>();

// const options = ref<PropertyDropdownOption[]>([]);

// const options = computed(() => {
//   return optionList.value;
//   // if (props.row.key === PropertyKey.Customization_DiagramTypeFilter_DiagramType) {
//   //   return optionsCustum.value || [];
//   // }
//   // else {
//   //   return optionList.value || optionsCustum || [];
//   // }

// });
// const optionsCustum = ref<PropertyDropdownOption[]>([]);
const clientY = ref(0);

const handleClick = (target: MouseEvent) => {
  clientY.value = target.clientY;
};
const selectedValue = computed(() => {
  if (props.row.key === PropertyKey.Customization_DiagramTypeFilter_DiagramType && props.row.value) {
    let item = props.row.value as ModelValue;
    let enName = item.id.split("::")[1] || item.name;
    return locale.getTByKey("modelConfig." + enName, enName);
  }
  const id = (props.row.value as ModelValue)?.id;
  if (id) {
    const name = (props.row.value as ModelValue).name || "";
    return locale.getTByKey("modelIdToName." + id, name);
    // return (props.row.value as ModelValue).name;
  } else {
    return props.row.value as string;
  }
  // props.row.value
  // if (props.row.items) {
  //   if ((props.row.value as ModelValue)?.id) {
  //     return props.row.items.find(it => it.value === (props.row.value as ModelValue)?.id);
  //   } else {
  //     return props.row.items.find(it => it.value == props.row.value); // 当dataType是"Real"时value是数字但item中的value是字符串，因此使用==判断
  //   }

  // } else if (optionsCustum.value) {
  //   if ((props.row.value as ModelValue)?.id) {
  //     return optionsCustum.value.find(it => it.value === (props.row.value as ModelValue)?.id);
  //   } else {
  //     return optionsCustum.value.find(it => it.value == props.row.value); // 当dataType是"Real"时value是数字但item中的value是字符串，因此使用==判断
  //   }

  // } else {
  //   return null;
  // }
});

function handleClickItem(item: PropertyDropdownOption) {
  if ([PropertyKey.ItemFlow_name, PropertyKey.ItemFlow_direction].includes(props.row.key as any)) {
    app.$bus.emit(BusEvent.EDITOR_CHANGE, props.row, item.value);
    props.row.value = item.value;
  } else {
    // 更新属性是共性行为
    propertyUtil.updatePropertyAndFresh(props.row, item.value);
  }
}

async function loadFn() {
  const projectId = app.activeProject?.id;
  const modelId = props.row.modelId;
  let list: PropertyDropdownOption[];
  if (props.row.key === PropertyKey.Customization_DiagramTypeFilter_DiagramType) {
    list = await loadCustomizationDiagramTypeFilterDiagramTypeOptions();
  } else {
    list = await modelService.getPropertyItems(projectId!, modelId, props.row.key);
  }
  return list;
}
const { options, loadOptions } = useLoadItemsOptions(props.row, loadFn);

// let loading = false;
// let loaded = false;
// async function loadOptions() {
//   console.log('AAAA');
//   const projectId = app.activeProject?.id;
//   const modelId = props.row.modelId;
//   if (!projectId || !modelId || loaded || loading) return;

//   loading = true;
//   try {
//     if (props.row.key === PropertyKey.Customization_DiagramTypeFilter_DiagramType) {
//       options.value = await loadCustomizationDiagramTypeFilterDiagramTypeOptions();
//     } else {
//       options.value = await modelService.getPropertyItems(projectId, modelId, props.row.key);

//     }
//     loaded = true;

//   } finally {
//     loading = false;
//   }
// }

async function loadCustomizationDiagramTypeFilterDiagramTypeOptions() {
  let data = await modelService.diagramTypeFilter(app.activeProjectId);
  return data.map(item => {
    let enName = item.id.split("::")[1] || item.name;
    return {
      label: locale.getTByKey("modelConfig." + enName, enName),
      value: item.id,
      enLabel: enName
    };
  });
}

// onMounted(async () => {
//   if (props.row.key === PropertyKey.Customization_DiagramTypeFilter_DiagramType) {
//     let data = await modelService.diagramTypeFilter(app.activeProjectId);
//     optionsCustum.value = data.map(item => {
//       let enName = item.id.split("::")[1] || item.name;
//       return {
//         label: locale.getTByKey('modelConfig.' + enName, enName),
//         value: item.id,
//         enLabel: enName

//       };
//     });

//   }
// });
</script>
